package vip.xiaonuo.auth.modular.login.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.common.config.ConfigProperties;
import vip.xiaonuo.common.pojo.CommonResult;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Slf4j
@RestController
@RequestMapping("/client/wxmp")
@Api(value = "微信公众号配置信息", tags = "wxMpConfig")
public class WxConfigController {
    WxMpService wxMpService;
    @Resource
    private ConfigProperties configProperties;

    @PostConstruct
    public void init() {
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        configStorage.setAppId(configProperties.getWechatConf().getAppId());
        configStorage.setSecret(configProperties.getWechatConf().getSecret());
        configStorage.setToken(configProperties.getWechatConf().getToken());
        configStorage.setAesKey(configProperties.getWechatConf().getAseKey());
        wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(configStorage);
    }

    /**
     * 获得公众号配置
     *
     * @return
     */
    @GetMapping("/config")
    public CommonResult<WxJsapiSignature> getConfig(@RequestParam("url") String url) {
        WxJsapiSignature config = null;
        try {
            String decodeUrl = URLDecoder.decode(url, "utf-8");
            config = wxMpService.createJsapiSignature(decodeUrl);
            log.info("获取公众号配置={}", config);
        } catch (WxErrorException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("", e);
        }
        return CommonResult.data(config);
    }
}
